import tornado.web
import tornado.websocket

class LoginHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        error = ''
        self.render('login.html',error=error)
    def post(self):
        #获取登录用户的信息
        username = self.get_body_argument('username')
        password = self.get_body_argument('password')

        #模拟登录
        if username in ['kongkong','yiyi','jiaojiao'] and password=='123456':
            #self.set_cookie('username',username)
            self.set_secure_cookie('username',username)
            #self.redirect('/')
            self.render('chat.html',username=username)
        else:
            error = '账号或者密码错误'
            self.render('login.html',error=error)
class RegisterHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        error = ''
        self.render('register.html',error=error)
    def post(self):
        username = self.get_body_argument('username')
        password = self.get_body_argument('password')
        #此处省略验证
        self.write('注册成功')




class ChatHandler(tornado.websocket.WebSocketHandler):
    #创建一个容器用来保存所有的链接对象
    user_online = []

    #当用户登录成功触发这个函数

    def open(self, *args, **kwargs):
        self.user_online.append(self) #谁进入自动进入容器
        for user in self.user_online:
            username = self.get_cookie('username')
            #username = self.get_secure_cookie('username').decode('utf-8')
            user.write_message("系统提示:【%s进入聊天室】" % username)
    #接收前段发送过来的消息
    def on_message(self, message):
        username = self.get_cookie('username')
        #username = self.get_secure_cookie('username').decode('utf-8')
        for user in self.user_online:
            user.write_message("%s:%s" % (username,message))
    #如果有客户端退出聊天触发该函数
    def on_close(self):
        self.user_online.remove(self)  #从连接对象容器中移出
        for user in self.user_online:
            username = self.get_cookie('username')
            #username = self.get_secure_cookie('username').decode('utf-8')
            user.write_message("系统提示:【%s退出聊天室】" % username)